<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import type {UploadProps} from 'ant-design-vue'
import {Modal} from 'ant-design-vue'
import {Cropper} from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'
import {error, handleError, success, warning} from '@/utils/message'
import {validate} from '@/utils/validate'
import {SPACE, UPLOAD} from '@/constants/messages'
import {
  DeleteOutlined,
  FolderOpenOutlined,
  PictureOutlined,
  SettingOutlined,
  TeamOutlined,
  UploadOutlined,
  UserAddOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import MainLayout from '@/components/layout/MainLayout.vue'
import StorageDisplay from '@/components/common/StorageDisplay.vue'
import ProgressiveImage from '@/components/common/ProgressiveImage.vue'
import {fileApi, pictureApi, spaceApi} from '@/api'
import {useAuthStore} from '@/stores/modules/auth'
import type {SpaceUpdateDTO} from '@/types/dto/space'
import type {SpaceInviteVO, SpaceUserVO, SpaceVO} from '@/types/vo/space'
import type {PictureVO} from '@/types/vo/picture'
import {getRoleColor, getRoleText} from '@/constants/space'
import {PICTURE_CATEGORIES} from '@/constants/picture'
import {useCropper} from '@/composables/useCropper'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const loadingMembers = ref(false)
const generating = ref(false)
const updating = ref(false)
const uploading = ref(false)
const activeTab = ref('pictures')
const inviteModalVisible = ref(false)
const settingsModalVisible = ref(false)
const uploadModalVisible = ref(false)

const space = ref<SpaceVO | null>(null)
const pictures = ref<PictureVO[]>([])
const members = ref<SpaceUserVO[]>([])
const inviteCode = ref<SpaceInviteVO | null>(null)

// 封面裁剪
const {
  cropperModalVisible,
  cropperImageSrc,
  cropperRef,
  previewUrl: editCoverPreview,
  croppedFile: editCoverFile,
  handleFileSelect: handleEditCoverChange,
  zoom,
  rotate,
  flip,
  reset,
  confirm: handleCropperConfirm,
  cancel: handleCropperCancel,
  aspectRatio
} = useCropper({
  maxSize: 5,
  aspectRatio: 3,
  shape: 'rect'
})

const uploadFileList = ref<any[]>([])
const uploadPreview = ref('')
const uploadFile = ref<File | null>(null)

interface UploadForm {
  pictureName: string
  introduction?: string
  category?: string
  tags?: string[]
}

const uploadForm = reactive<UploadForm>({
  pictureName: '',
  introduction: '',
  category: undefined,
  tags: []
})

const settingsForm = reactive<SpaceUpdateDTO>({
  spaceName: '',
  spaceDesc: '',
  coverUrl: '',
  memberLimit: undefined
})

// 权限判断
const isOwner = computed(() => space.value?.currentUserRole === 'owner')
const isEditor = computed(() => {
  const role = space.value?.currentUserRole
  return role === 'owner' || role === 'editor'
})

// 加载空间详情
const loadSpace = async () => {
  const id = Number(route.params.id)
  if (!id) {
    error('空间ID无效')
    router.push('/space')
    return
  }

  loading.value = true
  try {
    space.value = await spaceApi.getById(id)
    loadPictures()
    loadMembers()
  } catch (error: any) {
    handleError(error, SPACE.LOAD_FAILED)
    router.push('/space')
  } finally {
    loading.value = false
  }
}

// 加载图片列表
const loadPictures = async () => {
  if (!space.value) return
  try {
    const result = await pictureApi.list({
      spaceId: space.value.id,
      current: 1,
      size: 20
    })
    pictures.value = result.records
  } catch (error: any) {
    // 静默失败，不影响主流程
  }
}

// 加载成员列表
const loadMembers = async () => {
  if (!space.value) return
  loadingMembers.value = true
  try {
    const result = await spaceApi.getMembers(space.value.id!)
    members.value = result.list
  } catch (error: any) {
    handleError(error, SPACE.MEMBER_LOAD_FAILED)
  } finally {
    loadingMembers.value = false
  }
}

// 显示邀请对话框
const showInviteModal = () => {
  inviteCode.value = null
  inviteModalVisible.value = true
}

// 生成邀请码
const handleGenerateInvite = async () => {
  if (!space.value) return
  generating.value = true
  try {
    inviteCode.value = await spaceApi.generateInviteCode(space.value.id!)
    success(SPACE.INVITE_GENERATED)
  } catch (error: any) {
    handleError(error, SPACE.INVITE_FAILED)
  } finally {
    generating.value = false
  }
}

// 复制邀请码
const copyInviteCode = async () => {
  if (!inviteCode.value) return
  try {
    await navigator.clipboard.writeText(inviteCode.value.inviteCode)
    success(SPACE.INVITE_COPIED)
  } catch (err) {
    error(SPACE.COPY_FAILED)
  }
}

// 显示设置对话框
const showSettingsModal = () => {
  if (!space.value) return
  settingsForm.spaceName = space.value.spaceName
  settingsForm.spaceDesc = space.value.spaceDesc
  settingsForm.coverUrl = space.value.coverUrl
  settingsForm.memberLimit = space.value.memberLimit
  editCoverPreview.value = ''
  editCoverFile.value = null
  settingsModalVisible.value = true
}

// 更新空间设置
const handleUpdateSettings = async () => {
  if (!space.value) return
  updating.value = true
  try {
    let coverUrl = settingsForm.coverUrl

    // 如果有新封面，先上传
    if (editCoverFile.value) {
      coverUrl = await fileApi.uploadCover(editCoverFile.value)
    }

    // 更新空间设置
    space.value = await spaceApi.update(space.value.id!, {
      ...settingsForm,
      coverUrl: coverUrl || undefined
    })
    settingsModalVisible.value = false
    success(SPACE.UPDATE_SUCCESS)
  } catch (error: any) {
    handleError(error, SPACE.UPDATE_FAILED)
  } finally {
    updating.value = false
  }
}

// 显示上传对话框
const showUploadModal = () => {
  uploadModalVisible.value = true
  uploadForm.pictureName = ''
  uploadForm.introduction = ''
  uploadForm.category = undefined
  uploadForm.tags = []
  uploadPreview.value = ''
  uploadFile.value = null
  uploadFileList.value = []
}

// 上传前验证
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    handleError('只能上传图片文件！')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    handleError('图片大小不能超过 10MB！')
    return false
  }

  return false // 阻止自动上传
}

// 上传文件变化
const handleUploadChange: UploadProps['onChange'] = (info) => {
  const file = info.file.originFileObj || info.file

  if (file) {
    uploadFile.value = file as File
    uploadFileList.value = [info.file]

    // 生成预览
    const reader = new FileReader()
    reader.onload = (e) => {
      uploadPreview.value = e.target?.result as string
    }
    reader.readAsDataURL(file as File)

    // 如果没有填写图片名称，使用文件名
    if (!uploadForm.pictureName) {
      const fileName = (file as File).name || ''
      uploadForm.pictureName = fileName.replace(/\.[^/.]+$/, '')
    }
  }
}

// 移除上传文件
const removeUploadFile = () => {
  uploadPreview.value = ''
  uploadFile.value = null
  uploadFileList.value = []
}

// 执行上传
const handleUpload = async () => {
  if (!uploadFile.value) {
    warning(UPLOAD.FILE_REQUIRED)
    return
  }

  if (!validate.required(uploadForm.pictureName)) {
    warning('请输入图片名称')
    return
  }

  if (!space.value) return

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', uploadFile.value)
    formData.append('spaceId', space.value.id!.toString())
    formData.append('pictureName', uploadForm.pictureName.trim())

    if (uploadForm.introduction && uploadForm.introduction.trim()) {
      formData.append('introduction', uploadForm.introduction.trim())
    }
    if (uploadForm.category) {
      formData.append('category', uploadForm.category)
    }
    if (uploadForm.tags && uploadForm.tags.length > 0) {
      formData.append('tags', uploadForm.tags.join(','))
    }

    await pictureApi.upload(formData)
    success(UPLOAD.SUCCESS)
    uploadModalVisible.value = false

    // 刷新图片列表
    await loadPictures()
  } catch (error: any) {
    handleError(error, UPLOAD.FAILED)
  } finally {
    uploading.value = false
  }
}

// 成员操作
const handleMemberAction = async (action: string, member: SpaceUserVO) => {
  if (!space.value) return

  if (action === 'remove') {
    try {
      await spaceApi.removeMember(space.value.id!, member.userId)
      success(SPACE.MEMBER_REMOVED)
      loadMembers()
    } catch (error: any) {
      handleError(error, SPACE.MEMBER_REMOVE_FAILED)
    }
  } else {
    try {
      await spaceApi.updateMemberRole(space.value.id!, member.userId, {userRole: action})
      success(SPACE.ROLE_UPDATED)
      loadMembers()
    } catch (error: any) {
      handleError(error, SPACE.UPDATE_FAILED)
    }
  }
}

// 格式化日期
const formatDate = (date?: string) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : ''
}

// 删除空间
const handleDeleteSpace = async () => {
  if (!space.value) return

  try {
    await spaceApi.delete(space.value.id!)
    success(SPACE.DELETED)
    settingsModalVisible.value = false
    // 跳转回空间列表
    router.push('/space')
  } catch (error: any) {
    handleError(error, SPACE.DELETE_FAILED)
  }
}

// 退出空间
const handleLeaveSpace = () => {
  if (!space.value) return

  Modal.confirm({
    title: '退出空间',
    content: `确定要退出空间"${space.value.spaceName}"吗？退出后将无法访问空间内的图片。`,
    okText: '确定退出',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        if (!space.value || !authStore.user) return

        await spaceApi.removeMember(space.value.id!, authStore.user.id)
        success(SPACE.LEAVE_SUCCESS)
        // 跳转回空间列表
        router.push('/space')
      } catch (error: any) {
        handleError(error, SPACE.LEAVE_FAILED)
      }
    }
  })
}

onMounted(() => {
  loadSpace()
})
</script>

<template>
  <main-layout>
    <div class="space-detail-wrapper">
      <a-spin :spinning="loading">
        <div v-if="space">
          <!-- 空间封面背景 -->
          <div class="space-header-banner">
            <div v-if="space.coverUrl" class="banner-cover">
              <progressive-image :lazy="false" :src="space.coverUrl" alt="空间封面" class="banner-image" fit="cover"/>
              <div class="banner-overlay"></div>
            </div>
            <div v-else class="banner-gradient"></div>

            <div class="banner-content">
              <!-- 顶部操作栏 -->
              <div class="banner-top-bar">
                <a-button class="back-btn" shape="circle" size="large" @click="$router.back()">
                  ←
                </a-button>
                <div class="space-actions">
                  <a-button v-if="space.spaceType === 1 && isEditor" size="large" type="primary"
                            @click="showInviteModal">
                    <UserAddOutlined/>
                    邀请成员
                  </a-button>
                  <a-button v-if="isOwner" size="large" @click="showSettingsModal">
                    <SettingOutlined/>
                    设置
                  </a-button>
                </div>
              </div>

              <!-- 空间信息 -->
              <div class="space-title-info">
                <h1>{{ space.spaceName }}</h1>
                <p v-if="space.spaceDesc">{{ space.spaceDesc }}</p>
                <a-tag :color="space.spaceType === 0 ? 'blue' : 'green'" class="space-type-tag">
                  {{ space.spaceType === 0 ? '私有空间' : '团队空间' }}
                </a-tag>
              </div>
            </div>
          </div>

          <!-- 空间统计卡片 -->
          <div class="space-stats-section">
            <a-card :bordered="false">
              <a-row :gutter="24">
                <a-col :lg="space.spaceType === 0 ? 8 : 6" :md="12" :xs="24">
                  <div class="stat-item">
                    <PictureOutlined class="stat-icon"/>
                    <div class="stat-content">
                      <div class="stat-value">{{ space.usage?.currentPictureCount || 0 }}</div>
                      <div class="stat-label">
                        图片
                        <span v-if="space.maxPictureCount && space.maxPictureCount !== -1" class="stat-limit">
                          / {{ space.maxPictureCount }}
                        </span>
                      </div>
                    </div>
                  </div>
                </a-col>
                <a-col v-if="space.spaceType === 1" :lg="6" :md="12" :xs="24">
                  <div class="stat-item">
                    <TeamOutlined class="stat-icon"/>
                    <div class="stat-content">
                      <div class="stat-value">{{ space.usage?.currentMemberCount || 1 }}</div>
                      <div class="stat-label">
                        成员
                        <span v-if="space.memberLimit" class="stat-limit">/ {{ space.memberLimit }}</span>
                      </div>
                    </div>
                  </div>
                </a-col>
                <a-col :lg="space.spaceType === 0 ? 16 : 12" :md="24" :xs="24">
                  <storage-display
                      :total="space.maxStorageSize || 0"
                      :used="space.usage?.currentStorageSize || 0"
                      mode="compact"
                  />
                </a-col>
              </a-row>
            </a-card>
          </div>

          <!-- 标签页 -->
          <div class="space-detail-container">
            <a-card :bordered="false">
              <a-tabs v-model:activeKey="activeTab">
                <!-- 图片列表 -->
                <a-tab-pane key="pictures" tab="图片">
                  <!-- 上传按钮（只有编辑者和所有者可以上传） -->
                  <div v-if="isEditor" style="margin-bottom: 16px;">
                    <a-button size="large" type="primary" @click="showUploadModal">
                      <template #icon>
                        <UploadOutlined/>
                      </template>
                      上传图片到此空间
                    </a-button>
                  </div>

                  <div v-if="pictures.length > 0" class="pictures-grid">
                    <div
                        v-for="picture in pictures"
                        :key="picture.id"
                        class="picture-item"
                        @click="$router.push(`/picture/${picture.id}`)"
                    >
                      <progressive-image
                          :alt="picture.pictureName"
                          :lazy="true"
                          :src="picture.thumbnailUrl || picture.fileUrl"
                      />
                      <div class="picture-name">{{ picture.pictureName }}</div>
                    </div>
                  </div>
                  <a-empty v-else description="暂无图片">
                    <template #description>
                      <div style="margin-top: 16px;">
                        <p>这个空间还没有图片</p>
                        <a-button v-if="isEditor" type="primary" @click="showUploadModal">
                          <template #icon>
                            <UploadOutlined/>
                          </template>
                          立即上传
                        </a-button>
                      </div>
                    </template>
                  </a-empty>
                </a-tab-pane>

                <!-- 成员列表（只在团队空间显示） -->
                <a-tab-pane v-if="space.spaceType === 1" key="members" tab="成员">
                  <a-list :data-source="members" :loading="loadingMembers">
                    <template #renderItem="{ item }">
                      <a-list-item>
                        <a-list-item-meta>
                          <template #avatar>
                            <a-avatar :src="item.user?.userAvatar">
                              {{ item.user?.userName?.charAt(0) || 'U' }}
                            </a-avatar>
                          </template>
                          <template #title>
                            {{ item.user?.userName || '未知用户' }}
                          </template>
                          <template #description>
                            加入时间: {{ formatDate(item.joinTime) }}
                          </template>
                        </a-list-item-meta>

                        <template #actions>
                          <a-tag :color="getRoleColor(item.userRole)">
                            {{ getRoleText(item.userRole) }}
                          </a-tag>

                          <!-- Owner对其他成员的操作 -->
                          <a-dropdown v-if="isOwner && item.userId !== space.userId">
                            <a-button size="small">管理</a-button>
                            <template #overlay>
                              <a-menu @click="(e: any) => handleMemberAction(e.key, item)">
                                <a-menu-item v-if="item.userRole !== 'editor'" key="editor">
                                  设为编辑者
                                </a-menu-item>
                                <a-menu-item v-if="item.userRole !== 'viewer'" key="viewer">
                                  设为查看者
                                </a-menu-item>
                                <a-menu-divider/>
                                <a-menu-item key="remove" danger>移除成员</a-menu-item>
                              </a-menu>
                            </template>
                          </a-dropdown>

                          <!-- 非Owner成员可以退出空间 -->
                          <a-button
                              v-if="!isOwner && item.userId === authStore.user?.id"
                              danger
                              size="small"
                              @click="handleLeaveSpace"
                          >
                            退出空间
                          </a-button>
                        </template>
                      </a-list-item>
                    </template>
                  </a-list>
                </a-tab-pane>
              </a-tabs>
            </a-card>
          </div>
        </div>
      </a-spin>

      <!-- 邀请成员对话框 -->
      <a-modal
          v-model:open="inviteModalVisible"
          :confirm-loading="generating"
          title="邀请成员"
          @ok="handleGenerateInvite"
      >
        <div v-if="inviteCode">
          <a-alert message="邀请码已生成" style="margin-bottom: 16px" type="success"/>
          <a-input-group compact>
            <a-input
                :value="inviteCode.inviteCode"
                readonly
                style="width: calc(100% - 80px)"
            />
            <a-button type="primary" @click="copyInviteCode">
              复制
            </a-button>
          </a-input-group>
          <p style="margin-top: 12px; color: #999; font-size: 12px">
            ⏰ 有效期：3天（72小时）
          </p>
        </div>
        <p v-else>点击确定生成邀请码</p>
      </a-modal>

      <!-- 上传图片对话框 -->
      <a-modal
          v-model:open="uploadModalVisible"
          :confirm-loading="uploading"
          title="上传图片到空间"
          width="700px"
          @ok="handleUpload"
      >
        <a-form layout="vertical">
          <!-- 文件选择 -->
          <a-form-item label="选择图片" required>
            <div v-if="!uploadPreview" class="upload-zone">
              <a-upload
                  :before-upload="beforeUpload"
                  :file-list="uploadFileList"
                  :show-upload-list="false"
                  accept="image/*"
                  @change="handleUploadChange"
              >
                <div class="upload-area-compact">
                  <PictureOutlined style="font-size: 40px; color: #999;"/>
                  <p style="margin-top: 8px;">点击选择图片</p>
                  <p style="font-size: 12px; color: #999;">支持 JPG、PNG、GIF、WEBP，不超过 10MB</p>
                </div>
              </a-upload>
            </div>
            <div v-else class="upload-preview-compact">
              <img :src="uploadPreview" alt="预览"/>
              <a-button size="small" type="link" @click="removeUploadFile">重新选择</a-button>
            </div>
          </a-form-item>

          <!-- 图片信息 -->
          <a-form-item label="图片名称" required>
            <a-input v-model:value="uploadForm.pictureName" :maxlength="100" placeholder="请输入图片名称"/>
          </a-form-item>

          <a-form-item label="图片简介">
            <a-textarea v-model:value="uploadForm.introduction" :maxlength="500" :rows="3"
                        placeholder="请输入图片简介"/>
          </a-form-item>

          <a-form-item label="分类">
            <a-select v-model:value="uploadForm.category" allowClear placeholder="选择分类（可选）">
              <a-select-option
                  v-for="cat in PICTURE_CATEGORIES"
                  :key="cat.value"
                  :value="cat.value"
              >
                {{ cat.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="标签">
            <a-select v-model:value="uploadForm.tags" :max-tag-count="5" mode="tags" placeholder="输入标签后按回车"/>
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal
          v-model:open="settingsModalVisible"
          :confirm-loading="updating"
          title="空间设置"
          @ok="handleUpdateSettings"
      >
        <a-form layout="vertical">
          <a-form-item label="空间名称">
            <a-input v-model:value="settingsForm.spaceName" :maxlength="30"/>
          </a-form-item>
          <a-form-item label="空间描述">
            <a-textarea v-model:value="settingsForm.spaceDesc" :maxlength="200" :rows="3"/>
          </a-form-item>

          <a-form-item label="空间封面">
            <div class="cover-upload">
              <div v-if="editCoverPreview || settingsForm.coverUrl" class="cover-preview">
                <progressive-image :lazy="false" :src="(editCoverPreview || settingsForm.coverUrl) as string"
                                   alt="封面预览" fit="cover"/>
              </div>
              <div v-else class="cover-preview-placeholder">
                <FolderOpenOutlined style="font-size: 48px; color: #ccc;"/>
                <p>选择封面图片</p>
              </div>
              <a-upload
                  :before-upload="handleEditCoverChange"
                  :show-upload-list="false"
                  accept="image/*"
              >
                <a-button block style="margin-top: 8px;">
                  <UploadOutlined/>
                  {{ editCoverPreview ? '重新选择' : '更换封面' }}
                </a-button>
              </a-upload>
              <p class="upload-hint">支持 JPG、PNG、GIF、WEBP，不超过 5MB，建议 1200x400 像素</p>
            </div>
          </a-form-item>

          <a-form-item v-if="space?.spaceType === 1" label="成员上限">
            <a-input-number
                v-model:value="settingsForm.memberLimit"
                :max="50"
                :min="1"
                style="width: 100%"
            />
          </a-form-item>
        </a-form>

        <!-- 危险操作区域 -->
        <a-divider/>
        <div class="danger-zone">
          <h4 style="color: #ff4d4f; margin-bottom: 8px;">危险操作</h4>
          <p style="margin-bottom: 12px; color: #666; font-size: 13px;">
            删除空间后，空间内的所有图片和数据将无法恢复，请谨慎操作。
          </p>
          <a-popconfirm
              cancel-text="取消"
              ok-text="确定删除"
              ok-type="danger"
              placement="topRight"
              title="确定要删除这个空间吗？此操作不可恢复！"
              @confirm="handleDeleteSpace"
          >
            <a-button block danger>
              <template #icon>
                <DeleteOutlined/>
              </template>
              删除空间
            </a-button>
          </a-popconfirm>
        </div>
      </a-modal>

      <!-- 封面裁剪对话框 -->
      <a-modal
          v-model:open="cropperModalVisible"
          :width="900"
          cancel-text="取消"
          ok-text="确认"
          title="调整空间封面（3:1宽屏比例）"
          @cancel="handleCropperCancel"
          @ok="handleCropperConfirm"
      >
        <div class="cropper-container">
          <cropper
              ref="cropperRef"
              :src="cropperImageSrc"
              :stencil-props="{aspectRatio}"
              class="cropper"
          />
          <div class="cropper-toolbar">
            <a-space :size="12">
              <a-button size="small" @click="zoom(1.1)">放大</a-button>
              <a-button size="small" @click="zoom(0.9)">缩小</a-button>
              <a-button size="small" @click="rotate(90)">旋转</a-button>
              <a-button size="small" @click="flip(true, false)">翻转</a-button>
              <a-button size="small" @click="reset">重置</a-button>
            </a-space>
          </div>
          <p class="cropper-hint">💡 拖动调整位置，滚轮缩放大小</p>
        </div>
      </a-modal>
    </div>
  </main-layout>
</template>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as *;
@use '@/assets/styles/components.scss' as *;

.space-detail-wrapper {
  min-height: 100vh;
}

// 空间封面背景 Banner
.space-header-banner {
  position: relative;
  height: 400px;
  overflow: hidden;
  margin-bottom: -80px;

  @include responsive($breakpoint-md) {
    height: 300px;
    margin-bottom: -60px;
  }

  .banner-cover {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;

    .banner-image {
      width: 100%;
      height: 100%;

      :deep(.progressive-image) {
        height: 100%;
        border-radius: 0;
      }

      :deep(img) {
        object-fit: cover;
      }
    }

    .banner-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.6));
    }
  }

  .banner-gradient {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: $gradient-primary;
  }

  .banner-content {
    position: relative;
    z-index: 2;
    max-width: 1400px;
    margin: 0 auto;
    padding: $spacing-2xl $spacing-xl;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    color: white;

    @include responsive($breakpoint-md) {
      padding: $spacing-xl $spacing-lg;
    }

    .banner-top-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: $spacing-xl;

      .back-btn {
        background: rgba(255, 255, 255, 0.2);
        border: 2px solid rgba(255, 255, 255, 0.6);
        color: white;
        font-size: 20px;
        font-weight: bold;
        backdrop-filter: blur(10px);

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          border-color: white;
          transform: translateX(-4px);
        }
      }

      .space-actions {
        display: flex;
        gap: $spacing-md;

        :deep(.ant-btn) {
          box-shadow: $shadow-lg;
          backdrop-filter: blur(10px);

          &:hover {
            transform: translateY(-2px);
            box-shadow: $shadow-2xl;
          }
        }

        :deep(.ant-btn-primary) {
          background: white;
          color: $primary-color;
          border: none;

          &:hover {
            background: white !important;
            color: $primary-dark !important;
          }
        }

        :deep(.ant-btn:not(.ant-btn-primary)) {
          background: rgba(255, 255, 255, 0.2);
          border: 2px solid rgba(255, 255, 255, 0.6);
          color: white;

          &:hover {
            background: rgba(255, 255, 255, 0.3) !important;
            border-color: white !important;
          }
        }
      }
    }

    .space-title-info {
      h1 {
        font-size: $font-5xl;
        font-weight: $font-extrabold;
        margin: 0 0 $spacing-md 0;
        color: white;
        text-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);

        @include responsive($breakpoint-md) {
          font-size: $font-3xl;
        }
      }

      p {
        font-size: $font-lg;
        margin: 0 0 $spacing-md 0;
        opacity: 0.95;
        text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      }

      .space-type-tag {
        backdrop-filter: blur(8px);
        border: 1px solid rgba(255, 255, 255, 0.3);
        font-weight: $font-semibold;
      }
    }
  }
}

// 统计区域
.space-stats-section {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 $spacing-xl;
  position: relative;
  z-index: 3;

  @include responsive($breakpoint-md) {
    padding: 0 $spacing-lg;
  }

  :deep(.ant-card) {
    border-radius: $radius-2xl;
    box-shadow: $shadow-xl;
    border: none;
  }

  .stat-item {
    display: flex;
    align-items: center;
    gap: $spacing-lg;
    padding: $spacing-md 0;

    .stat-icon {
      font-size: 40px;
      color: $primary-color;
      width: 60px;
      height: 60px;
      @include flex-center;
      background: $gradient-bg;
      border-radius: $radius-lg;
    }

    .stat-content {
      flex: 1;

      .stat-value {
        font-size: $font-3xl;
        font-weight: $font-extrabold;
        color: $text-primary;
        line-height: 1.2;
      }

      .stat-label {
        font-size: $font-sm;
        color: $text-tertiary;
        margin-top: $spacing-xs;

        .stat-limit {
          color: $text-secondary;
        }
      }
    }
  }
}

.space-detail-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: $spacing-xl;

  @include responsive($breakpoint-md) {
    padding: $spacing-lg;
  }

  :deep(.ant-card) {
    border-radius: $radius-2xl;
    box-shadow: $shadow-lg;
    border: none;
  }
}

.pictures-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: $spacing-lg;

  @include responsive($breakpoint-md) {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: $spacing-md;
  }
}

.picture-item {
  @include card;
  cursor: pointer;
  border-radius: $radius-xl;
  overflow: hidden;
  background: white;
  transition: $transition-all;

  &:hover {
    transform: translateY(-6px) scale(1.02);
    box-shadow: $shadow-primary-hover;

    :deep(.progressive-image img) {
      transform: scale(1.1);
    }
  }

  :deep(.progressive-image) {
    width: 100%;
    border-radius: 0;

    img {
      transition: $transition-transform;
    }
  }

  .picture-name {
    padding: $spacing-md;
    font-size: $font-sm;
    font-weight: $font-medium;
    color: $text-primary;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.cover-upload {
  @include cover-upload;

  .cover-preview {
    :deep(.progressive-image) {
      height: 100%;
      border-radius: 0;
    }

    :deep(img) {
      object-fit: cover;
    }
  }
}

.upload-area-compact {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 32px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #1890ff;
    background: #f0f7ff;
  }

  p {
    margin: 0;
    color: #666;

    &:last-child {
      margin-top: 4px;
    }
  }
}

.upload-preview-compact {
  text-align: center;

  img {
    max-width: 100%;
    max-height: 300px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.cropper-container {
  @include cropper-container;
}

.danger-zone {
  @include danger-zone;
}
</style>